package com.pf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pf.common.enums.JobStatusEnum;
import com.pf.common.helper.ScheduledJobHelper;
import com.pf.dto.request.JobAddReq;
import com.pf.dto.request.JobUpdateReq;
import com.pf.dto.request.LogListReq;
import com.pf.dto.response.JobInfoResp;
import com.pf.enums.BaseResultEnum;
import com.pf.exception.BusinessException;
import com.pf.mapper.JobInfoMapper;
import com.pf.mapper.entity.JobInfo;
import com.pf.service.JobInfoService;
import com.pf.service.LogInfoService;
import com.pf.utils.DTOUtils;
import com.pf.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;

/**
 * @author PanFei
 * @version 1.0.0
 * @createTime 2021/8/10
 */
@Service
public class JobInfoServiceImpl implements JobInfoService {

    @Autowired
    private JobInfoMapper jobInfoMapper;
    @Autowired
    private ScheduledJobHelper scheduledJobHelper;
    @Autowired
    private LogInfoService logInfoService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addJobInfo(JobAddReq jobReq) {
        JobInfo jobInfo = DTOUtils.copyToNewObj(jobReq, JobInfo.class);
        jobInfo.setJobId(StringUtil.uuid());
        jobInfo.setStatus(JobStatusEnum.DISABLED.getCode());
        jobInfoMapper.insert(jobInfo);
    }

    @Override
    public void startJob(String jobId) {
        // 修改任务状态信息，修改为已启用
        JobInfo jobInfo = getJobByJobId(jobId);
        jobInfo.setStatus(JobStatusEnum.ENABLED.getCode());
        jobInfoMapper.updateById(jobInfo);

        // 将任务信息添加到线程池中
        scheduledJobHelper.start(jobInfo);

    }

    @Override
    public void stopJob(String jobId) {
        // 修改任务状态信息，修改为已停用
        JobInfo jobInfo = getJobByJobId(jobId);
        jobInfo.setStatus(JobStatusEnum.DISABLED.getCode());
        jobInfoMapper.updateById(jobInfo);

        // 停用线程池中的任务
        scheduledJobHelper.stop(jobId);
    }

    @Override
    public List<JobInfoResp> getJobInfoList(LogListReq logListReq) {
        List<JobInfo> jobInfos = jobInfoMapper.selectList(new LambdaQueryWrapper<JobInfo>()
                .eq(JobInfo::getIsDeleted, 0)
                .like(StringUtils.isNotBlank(logListReq.getJobName()), JobInfo::getJobName, logListReq.getJobName())
                .like(StringUtils.isNotBlank(logListReq.getJobUrl()), JobInfo::getJobUrl, logListReq.getJobUrl())
                .orderByDesc(JobInfo::getUpdatedDate)
        );
        return DTOUtils.copyToNewObjList(jobInfos, JobInfoResp.class);
    }

    @Override
    public JobInfoResp getJobInfo(String jobId) {
        JobInfo jobInfo = getJobByJobId(jobId);
        return DTOUtils.copyToNewObj(jobInfo, JobInfoResp.class);
    }

    @Override
    public void updateJobInfo(JobUpdateReq jobReq) {
        Assert.notNull(jobReq, "任务信息不能为空！");
        String jobId = jobReq.getJobId();
        // 校验任务是否存在
        JobInfo jobInfo = getJobByJobId(jobId);
        if (jobInfo == null) {
            throw new BusinessException(BaseResultEnum.JOB_NOT_EXISTS);
        }
        // 校验是否有运行中的任务
//        if (logInfoService.isExistsRunningJob(jobId)) {
//            throw new BusinessException(BaseResultEnum.JOB_IS_RUNNING);
//        }

        // 修改任务
        BeanUtils.copyProperties(jobReq, jobInfo);
        jobInfoMapper.updateById(jobInfo);

    }

    /**
     * 通过jobId查询对应任务信息
     *
     * @param jobId
     * @return
     */
    private JobInfo getJobByJobId(String jobId) {
        return jobInfoMapper.selectOne(new LambdaQueryWrapper<JobInfo>()
                .eq(JobInfo::getJobId, jobId)
                .eq(JobInfo::getIsDeleted, 0)
        );
    }

}
